import keras
import cv2
import numpy as np

# 加载反卷积的训练模型
unet = keras.models.load_model("unet.h5")

# -------------------------加载车牌图像，检测车牌区域-----------------------------
img_src_path = "test3.jpg"
image = cv2.imdecode(np.fromfile(img_src_path,dtype=np.uint8),-1)
print(image.shape)
if image.shape != (512,512,3):
    image = cv2.resize(image, dsize=(512, 512), interpolation=cv2.INTER_AREA)[:, :, :3]
image = image.reshape(1,512,512,3)

img_mask = unet.predict(image)
img_mask = img_mask.reshape(512,512,3)
img_mask = img_mask / np.max(img_mask) * 255  # 将像素值控制到0- 255 之间
img_mask[:, :, 2] = img_mask[:, :, 1] = img_mask[:, :, 0]  # 三个通道保持相同
img_mask = np.array(img_mask,dtype=np.uint8)

try:
    # opencv3.0
    contours, hierarchy = cv2.findContours(img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
except:
    # opencv2.0
    ret, contours, hierarchy = cv2.findContours(img_mask[:, :, 0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

image = image.reshape(512,512,3)
cv2.drawContours(image,contours,-1,color=(0,255,0),thickness=2)
cv2.imshow("src",image)
cv2.waitKey(0)
cv2.destroyAllWindows()

